package com.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.dom4j.Attribute;
import org.dom4j.Element;

import com.excel.analysis.Analysis;
import com.excel.analysis.Calculation;
import com.excel.analysis.XMLHandler;

public class NaireServlet extends HttpServlet {

	private static final long serialVersionUID = 6386369124871460451L;

	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getRequestURI();
		action = action.substring(action.lastIndexOf("/") + 1);
		if (action.equals("createNaire.naire")) {
			File file = new File(this.getServletContext().getRealPath("/")
					+ "/data/data.xml");
			try {
				XMLHandler xMLHandler = new XMLHandler(file);
				req.getSession().setAttribute("xMLHandler", xMLHandler);
				resp.setCharacterEncoding("utf-8");
				resp.getWriter().write(xMLHandler.toXml());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("answer.naire")) {
			String id = req.getParameter("id");
			boolean selected = Boolean.parseBoolean(req
					.getParameter("selected"));
			try {
				XMLHandler xMLHandler = (XMLHandler) req.getSession()
						.getAttribute("xMLHandler");
				if (xMLHandler == null) {
					return;
				}
				Element node = (Element) xMLHandler
						.selectSingleNode("//*[@id='" + id + "']");
				if (node.getName().equals("item")) {
					Element parent = node.getParent();
					String type = parent.attributeValue("type");
					if (!type.equals("mutil")) {
						// 单选
						Element _node = (Element) parent.selectSingleNode("item[@selected='y']");
						if (_node != null) {
							Attribute _attribute = _node.attribute("selected");
							_attribute.setValue("n");
						}
						node.attribute("selected").setValue("y");
					} else {
						// 复选
						Attribute attribute = node.attribute("selected");
						if (selected) {
							attribute.setValue("y");
						} else {
							attribute.setValue("n");
						}
					}
				} else if(node.getName().equals("entry")) {
					Attribute attribute = node.attribute("use");
					if (selected) {
						attribute.setValue("y");
					} else {
						attribute.setValue("n");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("submit.naire")) {
			XMLHandler xMLHandler = (XMLHandler) req.getSession().getAttribute(
					"xMLHandler");
			xMLHandler.saveAs(new File(this.getServletContext()
					.getRealPath("/")
					+ "/datas/"
					+ format.format(new Date())
					+ ".xml"));
			req.getRequestDispatcher("/list.naire").forward(req, resp);
		} else if (action.equals("list.naire")) {
			File file = new File(this.getServletContext().getRealPath("/")
					+ "/datas/");
			File[] files = file.listFiles();
			List<Map<String, String>> l = new ArrayList<Map<String, String>>();
			for (File f : files) {
				Map<String, String> m = new HashMap<String, String>();
				m.put("size", String.valueOf(Math.floor(f.length() / 1024))
						+ "kb");
				m.put("fileName", f.getName());
				l.add(m);
			}
			req.setAttribute("list", l);
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else if (action.equals("view.naire")) {
			String f = req.getParameter("file");
			File file = new File(this.getServletContext().getRealPath("/")
					+ "/datas/" + f);
			XMLHandler xMLHandler;
			try {
				xMLHandler = new XMLHandler(file);
				resp.setCharacterEncoding("utf-8");
				resp.getWriter().write(xMLHandler.toXml());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("upload.naire")) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);
			sfu.setFileSizeMax(1024 * 1024 * 20);
			sfu.setSizeMax(1024 * 1024);
			sfu.setHeaderEncoding("UTF-8");
			try {
				@SuppressWarnings("unchecked")
				List<FileItem> list = sfu.parseRequest(req);
				for (FileItem fi : list) {
					if (!fi.isFormField()) {
						String name = fi.getName();
						File file = new File(this.getServletContext()
								.getRealPath("/") + "/upload/" + name);
						try {
							fi.write(file);
							Analysis ta = new Analysis(file.getPath(), 0);
							ta.analysisXml();
							XMLHandler xMLHandler = new XMLHandler(ta.toXml());
							xMLHandler.saveAs(new File(this.getServletContext()
									.getRealPath("/data/data.xml"))); // 保存文件
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			req.getRequestDispatcher("/list.naire").forward(req, resp);
		} else if (action.equals("calculate.naire")) {
			String f = req.getParameter("file");
			File file = new File(this.getServletContext().getRealPath("/") + "/datas/" + f);
			try {
				Calculation calculation = new Calculation(file);
				calculation.calulation();
			} catch (Exception e) {
				e.printStackTrace();
			}
			req.getRequestDispatcher("/list.naire").forward(req, resp);
		}
	}
}